#--------------------------------------------------------------------------------------------------------------------#
#------------------------------------------------------ Lea Portmann ------------------------------------------------#
#--------------------------------------------------------- May 2021 -------------------------------------------------#
#---------- What Makes a Successful Candidate? Political Experience and Low-Information Cues in Elections -----------#
#----------------------------- Analysis negative and positive preference votes --------------------------------------#
#--------------------------------------------------------------------------------------------------------------------#

library(interplot)
library(lme4)
library(gamlss)
library(nlme)
library(ggeffects)
library(texreg)
library(ggpubr)
library(GLMMadaptive)
library(glmmADMB)
library(emmeans)
library(glmmTMB)
library(dplyr)
library(gridExtra)
library(glmmTMB)
library(glmmADMB)
library(xtable)

#---------------------------------------------------------------------- Read data

rm(list=ls())
setwd(".../...")

load("d3")

#Drop incumbent candidates
d3_m <- d3[d3$incumbent == 0, ]

#Drop observations with missing values of dependent variable "negative preference votes"
d3_mn  <- d3_m[d3_m$n_pv != 0, ]

#Drop observations with missing values of dependent variable "positive preference votes"
d3_mp <- d3_m[d3_m$pos_rel!=0,]

#---------------------------------------------------------------------- Functions

### Coefficient plot

PlotCoefficients <- function(z) {
  z <- ggplot(allModelFrame, aes(colour = Model))
  z <- z + geom_hline(yintercept = 0, colour = gray(1/2), lty = 5)
  z <- z + geom_linerange(aes(x = Variable, ymin = Coefficient - SE*interval1,
                              ymax = Coefficient + SE*interval1),
                          lwd = 0.9, position = position_dodge(width = 1))
  z <- z + geom_linerange(aes(x = Variable, ymin = Coefficient - SE*interval11,
                              ymax = Coefficient + SE*interval11),
                          lwd = 1.4, position = position_dodge(width = 1))
  z <- z + geom_pointrange(aes(x = Variable, y = Coefficient, ymin = Coefficient - SE*interval1,
                               ymax = Coefficient + SE*interval1, shape = Model),
                           lwd = 0.5, position = position_dodge(width = 1)
                           #shape = c(3, 2, 1)
  )
  z <- z  + theme_bw() + coord_flip()
  z <- z + ggtitle("")
  return (z)}

### Marginal effects plot

marg_plot <- function(marg){
  marg <- ggplot(data) + 
    geom_hline(yintercept = 0, colour = gray(1/2), lty = 5) +
    geom_linerange(aes(x = contrast, color = col, ymin = estimate - SE*interval1,
                       ymax = estimate + SE*interval1), 
                   lwd = 0.9, position = position_dodge(width = 2)) +
    geom_pointrange(aes(x = contrast, color = col, y = estimate, ymin = estimate - SE*interval1,
                        ymax = estimate + SE*interval1),
                    lwd = 0.8, position = position_dodge(width = 2)) + 
    geom_linerange(aes(x = contrast, color = col, ymin = estimate - SE*interval11,
                       ymax = estimate + SE*interval11), 
                   lwd = 2, position = position_dodge(width = 2)) +
    coord_flip() + theme_bw(base_size=12) + theme_bw() + 
    scale_colour_manual(values = colors, aesthetics = c("colour", "fill")) + 
    scale_linetype_manual(guide = guide_legend(reverse = TRUE))
  return(marg)}

### Plot differences marginal effects

marg_diff_plot <- function(marg){
  marg <- ggplot(data) + 
    geom_hline(yintercept = 0, colour = gray(1/2), lty = 5) +
    geom_linerange(aes(x = contrast, ymin = estimate - SE*interval1,
                       ymax = estimate + SE*interval1), 
                   lwd = 0.9, position = position_dodge(width = 2)) +
    geom_pointrange(aes(x = contrast, y = estimate, ymin = estimate - SE*interval1,
                        ymax = estimate + SE*interval1),
                    lwd = 0.8, position = position_dodge(width = 2)) + 
    geom_linerange(aes(x = contrast, ymin = estimate - SE*interval11,
                       ymax = estimate + SE*interval11), 
                   lwd = 2, position = position_dodge(width = 2))  +
    coord_flip() + theme_bw(base_size=12) + theme_bw() +
    scale_linetype_manual(guide = guide_legend(reverse = TRUE)) +
    theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank()) +
    theme(plot.title = element_text(size=11)) + coord_flip()
  return(marg)}

#---------------------------------------------------------------------- Example modified ballots (in empirical approach)

names(d3_m)
table(d3_m$bfscantno)

ex_modeball <- d3_m %>% filter(bfscantno == 1)

table(ex_modeball$bfsparty_txt.y, ex_modeball$ballots_mod)

#--------------------------------------------------------------------------------------------#
#--------- PART 1a: Impact information about competence on preference votes
#--------------------------------------------------------------------------------------------#

#---------------------------------------------------------------------- Models

m1n <- glmmadmb(n_pv ~ nonswissname + relpos_c + precumulated + 
prof_c3 + sex_f + age_c3 + party_c4 + num_cand_c + 
poloff_d*TApoloff + nonelec_d_eff*TAnonelec + (1|list_id), 
family="beta", data = d3_mn)
summary(m1n)

m1p <- glmer(pos_rel ~ nonswissname + relpos_c + precumulated  +
prof_c3 + sex_f + age_c3 + party_c4 + num_cand_c + poloff_d*TApoloff + 
nonelec_d_eff*TAnonelec + (1| list_id), 
family= inverse.gaussian(link="log"), nAGQ=0, data=d3_mp)
summary(m1p)

#---------------------------------------------------------------------- Coefficient plot

#Specify 95% confidence intervals

interval1 <- -qnorm((1-0.95)/2)  # 95% multiplier
interval11 <- -qnorm((1-0.90)/2)  # 90% multiplier

#Change order of variables

order_var <- c("nonelec_d_effyes:TAnonelecT1", "poloff_dyes:TApoloffT1",
"nonelec_d_effyes", "poloff_dyes", 
"TAnonelecT1", "TApoloffT1", "age_c32", "age_c31", "sex_f", 
"prof_c33", "prof_c32", "nonswissname")

#Define labels

my_labels = c("(Intercept)" = "Intercept", 
              "poloff_dyes:TApoloffT1" = "Political office x Treatment political office", 
              "nonelec_d_effyes:TAnonelecT1" = "Nonelective office x Treatment nonelective office",
              "TAnonelecT1" = "Treatment nonelective office on ballot",
              "nonelec_d_effyes" =  "Nonelective office", 
              "TApoloffT1" =  "Treatment political office on ballot", 
              "poloff_dyes" =  "Political office", 
              "num_cand_c" =  "Number of candidates on ballot",
              "party_c43" =  "Party position = other", 
              "party_c42" = "Party position = left", 
              "party_c41" =  "Party position = center", 
              "age_c32" =  "Age: 50+ years", 
              "age_c31" =  "Age: 31-50 years", 
              "sex_f" =  "Female", 
              "prof_c33" =  "Profession = low-skilled", 
              "prof_c32" =  "Profession = medium-skilled", 
              "precumulated" =  "Pre-cumulated", 
              "relpos_c" =  "Relative position on ballot", 
              "nonswissname" =  "Non-Swiss name")

#Define theme

my_theme <- theme(axis.text.y = element_text(size = 12, colour = "black")) + theme(axis.text.x= element_text(size = 12, colour = "black")) +  
  theme(axis.title = element_text(size = 12)) + theme(legend.position="bottom") + theme(legend.title = element_text(size = 12)) + 
  theme(legend.text = element_text(size = 12)) + theme(plot.margin = unit(c(0,1,0,0), "cm")) 


# ------------------- Negative preference votes

model1Frame <- data.frame(Variable = rownames(summary(m1n)$coef),
                          Coefficient = summary(m1n)$coef[, 1],
                          SE = summary(m1n)$coef[, 2],
                          Model = "Negative preference votes")

allModelFrame <- model1Frame

allModelFrame$Variable <- factor(allModelFrame$Variable, levels=order_var)

#Drop commune fixed effects
cc=is.na(allModelFrame$Variable)
m=which(cc==c("TRUE"))
allModelFrame=allModelFrame [-m,]

#Coefficient plot
zneg <- PlotCoefficients(z)
zneg <- PlotCoefficients(z) + scale_y_continuous("", limits = c(-0.5, 0.5)) + scale_x_discrete("", labels = my_labels) +
  my_theme + theme(axis.text.y = element_text(face = c("bold", "bold", "plain", "plain", "plain", "plain", "plain", "plain", "plain", "plain", "plain", "plain", "plain", "plain", "bold"))) +
  scale_colour_manual("Model", values = "black") + theme(legend.title = element_blank())
zneg

# ------------------- Positive preference votes

model2Frame <- data.frame(Variable = rownames(summary(m1p)$coefficients),
                          Coefficient = summary(m1p)$coefficients[,1],
                          SE = summary(m1p)$coefficients[,2],
                          Model = "Positive preference votes")

allModelFrame <- model2Frame

allModelFrame$Variable <- factor(allModelFrame$Variable, levels=order_var)

#Drop commune fixed effects
cc=is.na(allModelFrame$Variable)
m=which(cc==c("TRUE"))
allModelFrame=allModelFrame [-m,]

zpos <- PlotCoefficients(z)
zpos <- PlotCoefficients(z) + scale_y_continuous("", limits = c(-0.5, 0.5)) + scale_x_discrete("", labels = my_labels) +
  my_theme + theme(axis.text.y = element_text(face = c("bold", "bold", "plain", "plain", "plain", "plain", "plain", "plain", "plain", "plain", "plain", "plain", "plain", "plain", "bold"))) +
  scale_colour_manual("Model", values = "gray60") + theme(legend.title = element_blank()) + 
  theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank())
zpos

mod_politexp <- grid.arrange(zneg, zpos,
                            ncol=2, nrow = 1,
                            widths = c(2.1, 1.2))
mod_politexp

#---------------------------------------------------------------------- Tables for appendix

custom.name.1 <- c("Intercept", "Non-Swiss name", 
                   "Relative position on ballot", 
                   "Pre-cumulated", "Profession = medium-skilled", 
                   "Profession: low-skilled", "Female", 
                   "Party position: center", "Party position: left",
                   "Party position: other", "Number of candidates on ballot",
                   "Age: 31-50 years ", "Age: 50+ years", 
                   "Non-elective office", "Political office")

m0n <- glmmadmb(n_pv ~ nonswissname + relpos_c + precumulated + 
                  prof_c3 + sex_f + age_c3 + party_c4 + num_cand_c +
                  poloff_d + nonelec_d_eff  +  (1|list_id), 
                family="beta", data = d3_mn)

m1n <- glmmadmb(n_pv ~ nonswissname + relpos_c + precumulated + 
                  prof_c3 + sex_f + age_c3 + party_c4 + num_cand_c + 
                  poloff_d*TApoloff + nonelec_d_eff*TAnonelec + (1|list_id), 
                family="beta", data = d3_mn)

custom.name.1 <- c("Intercept", "Non-Swiss name", 
                   "Relative position on ballot", 
                   "Pre-cumulated", "Profession = medium-skilled", 
                   "Profession: low-skilled", "Female", 
                   "Age: 31-50 years ", "Age: 50+ years", 
                   "Party position: center", "Party position = left",
                   "Party position: other", "Number of candidates on ballot",
                   "Political office","Non-elective office", 
                   "Political office on ballot",  
                   "Non-elective office on ballot", 
                   "Political office x Political office on ballot", 
                   "Non-elective office x Non-elective office on ballot")

texreg(list(m0n, m1n), booktabs=TRUE,
       omit.coef = "bfscantno",
       custom.coef.names = custom.name.1,
       #reorder.coef = c(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1),
       caption="Effect of ballot cues indicating political experience on negative preference votes",
       caption.above = TRUE, stars = c(0.001, 0.01, 0.05, 0.1))

m0p <- glmer(pos_rel ~ nonswissname + relpos_c + precumulated  +
               prof_c3 + sex_f + age_c3 + party_c4 + num_cand_c +
               poloff_d  + nonelec_d_eff + (1|list_id), nAGQ=0, family=inverse.gaussian(link="log"), data=d3_mp)

texreg(list(m0p, m1p), booktabs=TRUE,
       omit.coef = "bfscantno",
       #custom.coef.names = custom.name.1,
       reorder.coef = c(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1),
       caption="Effect of ballot cues indicating political experience on positive preference votes",
       caption.above = TRUE, stars = c(0.001, 0.01, 0.05, 0.1))

#---------------------------------------------------------------------- Interaction effects ideology

# ------------------- Models

d3_mn$party_c6_f <- factor(d3_mn$party_c6)
mn_ideol <- glmmTMB(n_pv ~ nonswissname*party_c6_f + relpos_c + precumulated + 
                  prof_c3 + sex_f + age_c3 + num_cand_c + 
                  poloff_d + nonelec_d_eff + 
                  (1|list_id), 
                  family=list(family="beta",link="logit"), data = d3_mn)
summary(mn_ideol)

d3_mp$party_c6_f <- factor(d3_mp$party_c6)
mp_ideol <- glmer(pos_rel ~ nonswissname*party_c6_f + relpos_c + precumulated  +
               prof_c3 + sex_f + age_c3 + num_cand_c +
               poloff_d  + nonelec_d_eff + (1|list_id), nAGQ=0, family=inverse.gaussian(link="log"), data=d3_mp)
summary(mp_ideol)

table(d3_mp$nonswissname, d3_mp$party_c6_f)

# ------------------- Tables

custom.name.1 <- c("Intercept", "Non-Swiss name", 
                  "Party position: center-right", "Party position: center", 
                   "Party position: center-left", "Party position: left", "Party position: other",
                  "Relative position on ballot", 
                   "Pre-cumulated", "Profession = medium-skilled", 
                   "Profession = low-skilled", "Female", 
                   "Age: 31-50 years ", "Age: 50+ years", 
                   "Number of candidates on ballot",
                   "Political office","Non-elective office", 
                   "Non-Swiss name x party position = center-right", 
                  "Non-Swiss name x party position = center", 
                  "Non-Swiss name x party position = center-left", 
                  "Non-Swiss name x party position = left", 
                  "Non-Swiss name x party position = other")

texreg(list(mn_ideol, mp_ideol), booktabs=TRUE,
       omit.coef = "bfscantno",
       custom.coef.names = custom.name.1,
       caption="Effect of candidate names (non-Swiss vs. Swiss) on negative preference votes, by ideological position of party",
       caption.above = TRUE, single.row = TRUE, stars = c(0.001, 0.01, 0.05, 0.1))

# ------------------- Marginal effects negative preference votes

emm <- regrid(emmeans(mn_ideol, ~ nonswissname | party_c6_f))
emm_pairs_data <- summary(pairs(emm, reverse = TRUE))
emm_pairspairs_data <- summary(pairs(pairs(emm), by = NULL))

# Figure

colors = c("grey80", "grey60", "grey50", "grey40", "grey20", "black")
emm_pairs_data$col <- factor(emm_pairs_data$party_c6_f, 
levels = c(5, 4, 3, 2, 1, 0), 
labels = c("Other", "Left", "Center-left", "Center", "Center-right", "Right"))
emm_pairs_data$contrast <- emm_pairs_data$col
data <- emm_pairs_data
marg_n_ideol <- marg_plot(marg)
marg_n_ideol <- marg_n_ideol + theme(legend.position="none") + 
labs(x="",  y="Effect of candidate name (non-Swiss vs. Swiss) on negative preference votes"); marg_n_ideol

# ------------------- Marginal effects positive preference votes

emm <- regrid(emmeans(mp_ideol, ~ nonswissname | party_c6_f))
emm_pairs_data <- summary(pairs(emm, reverse = TRUE))
emm_pairspairs_data <- summary(pairs(pairs(emm), by = NULL))

# Figure

colors = c("grey80", "grey60", "grey50", "grey40", "grey20", "black")
emm_pairs_data$col <- factor(emm_pairs_data$party_c6_f, 
levels = c(5, 4, 3, 2, 1, 0), 
labels = c("Other", "Left", "Center-left", "Center", "Center-right", "Right"))
emm_pairs_data$contrast <- emm_pairs_data$col
data <- emm_pairs_data
marg_p_ideol <- marg_plot(marg)
marg_p_ideol <- marg_p_ideol + theme(legend.position="none") + 
labs(x="",  y="Effect of candidate name (non-Swiss vs. Swiss) on positive preference votes"); marg_p_ideol


#--------------------------------------------------------------------------------------------#
#--------- PART 1b: Marginal effects
#--------------------------------------------------------------------------------------------#

#---------------------------------------------------------------------- Marginal effects negative preference votes

m1n <- glmmTMB(n_pv ~ nonswissname + relpos_c + precumulated + 
                 prof_c3 + sex_f + age_c3 + party_c4 + num_cand_c + 
                 TApoloff*poloff_d + TAnonelec*nonelec_d_eff + (1|list_id), 
                 family=list(family="beta",link="logit"), data = d3_mn)
summary(m1n)

# ------------------ Political offices

### Calculate marginal effects

emm <- regrid(emmeans(m1n, ~ poloff_d | TApoloff))
emm_data <- summary(regrid(emmeans(m1n, ~ poloff_d | TApoloff)))
emm_pairs_data <- summary(pairs(emm, reverse = TRUE))
emm_pairspairs_data <- summary(pairs(pairs(emm, reverse = TRUE), by = NULL, reverse = TRUE))

#plot(emm)

# Save marginal effects for later

marg_diff_T_poloff <- summary(pairs(pairs(emm), by = NULL))$estimate
marg_T0_poloff <- emm_pairs_data[1, 3]
marg_T1_poloff <- emm_pairs_data[2, 3]

#Figure marginal effects

colors = c("black", "grey50")
emm_pairs_data$col<- factor(emm_pairs_data$TApoloff, 
levels = c("T1", "T0"), 
labels = c("On ballot", "Not on ballot"))
data <- emm_pairs_data
marg_neg_pol <- marg_plot(marg)
marg_neg_pol <- marg_neg_pol + guides(fill=FALSE) + theme(legend.position="none") +
theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank()) +
labs(colour = "Political office", x="", y="Effect of political office on negative preference votes", title="A") +
annotate("text", x=0.35, y=-0.01, label = "Political offices on ballot", vjust=1, hjust=1, size = 3.3, color="black") +
annotate("text", x=1.35, y=-0.015, label = "Political offices not on ballot", vjust=1, hjust=1, size = 3.3, color="grey50"); marg_neg_pol

# Figure difference marginal effects

data <- emm_pairspairs_data
marg_neg_diff_pol <- marg_diff_plot(marg)
marg_neg_diff_pol <- marg_neg_diff_pol +  labs(colour = "Political office", x="", 
y="Difference of effects", title = "B") +
scale_colour_manual(values = colors, aesthetics = c("colour", "fill")) 

#  Save Figures

eff_diff_pol <- grid.arrange(marg_neg_pol, marg_neg_diff_pol, 
ncol=2, nrow = 1)
eff_diff_pol

# ------------------ Nonelective offices

### Calculate marginal effects

emm <- regrid(emmeans(m1n, ~ nonelec_d_eff | TAnonelec))
emm_data <- summary(regrid(emmeans(m1n, ~ poloff_d | TApoloff)))
emm_pairs_data <- summary(pairs(emm, reverse = TRUE))
emm_pairspairs_data <- summary(pairs(pairs(emm, reverse = TRUE), by = NULL, reverse = TRUE))

# Save marginal effects for later

marg_diff_T_nonelec <- summary(pairs(pairs(emm), by = NULL))$estimate
marg_T0_nonelec <- emm_pairs_data[1, 3]
marg_T1_nonelec <- emm_pairs_data[2, 3]

#Figure marginal effects

colors = c("black", "grey50")
emm_pairs_data$col <- factor(emm_pairs_data$TAnonelec, 
                                          levels = c("T1", "T0"), 
                                          labels = c("On ballot", "Not on ballot"))
data <- emm_pairs_data
marg_neg_nonelec <- marg_plot(marg)
marg_neg_nonelec <- marg_neg_nonelec + guides(fill=FALSE) + theme(legend.position="none") +
theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank()) +
labs(colour = "Nonelective office", x="", y="Effect of nonelective office on negative preference votes", title="A") +
annotate("text", x=0.35, y=-0.001, label = "Nonelective offices on ballot", vjust=1, hjust=1, size = 3.3, color="black") +
annotate("text", x=1.35, y=-0.003, label = "Nonelective offices not on ballot", vjust=1, hjust=1, size = 3.3, color="grey50"); marg_neg_nonelec 

# Figure difference marginal effects

data <- emm_pairspairs_data
marg_neg_diff_nonelec <- marg_diff_plot(marg)
marg_neg_diff_nonelec <- marg_neg_diff_nonelec +  labs(colour = "Nonelective office", x="", 
y="Difference of effects", 
title="B") +
scale_colour_manual(values = colors, aesthetics = c("colour", "fill")) 

# Save Figures

eff_diff_nonelec <- grid.arrange(marg_neg_nonelec, marg_neg_diff_nonelec, 
                              ncol=2, nrow = 1)
eff_diff_nonelec 

#---------------------------------------------------------------------- Marginal effects positive preference votes

# ------------------ Political offices

### Calculate marginal effects

emm <- regrid(emmeans(m1p, ~ poloff_d | TApoloff))
emm_data <- summary(regrid(emmeans(m1p, ~ poloff_d | TApoloff)))
emm_pairs_data <- summary(pairs(emm, reverse = TRUE))
emm_pairspairs_data <- summary(pairs(pairs(emm, reverse = TRUE), by = NULL, reverse = TRUE))

#plot(emm)

# Save marginal effects for later

marg_p_diff_T_poloff <- summary(pairs(pairs(emm), by = NULL))$estimate
marg_p_T0_poloff <- emm_pairs_data[1, 3]
marg_p_T1_poloff <- emm_pairs_data[2, 3]

#Figure marginal effects

colors = c("black", "grey50")
emm_pairs_data$col<- factor(emm_pairs_data$TApoloff, 
                            levels = c("T1", "T0"), 
                            labels = c("On ballot", "Not on ballot"))
data <- emm_pairs_data
marg_pos_pol <- marg_plot(marg)
marg_pos_pol <- marg_pos_pol + guides(fill=FALSE) + theme(legend.position="none") +
theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank()) +
labs(colour = "Political office", x="", y="Effect of political office on positive preference votes", title="A") +
annotate("text", x=0.35, y=0.2, label = "Political offices on ballot", vjust=1, hjust=1, size = 3.3, color="black") +
annotate("text", x=1.35, y=-0.02, label = "Political offices not on ballot", vjust=1, hjust=1, size = 3.3, color="grey50"); marg_pos_pol

# Figure difference marginal effects

data <- emm_pairspairs_data
marg_pos_diff_pol <- marg_diff_plot(marg)
marg_pos_diff_pol <- marg_pos_diff_pol +  labs(colour = "Political office", x="", 
y="Difference of effects", title="B") +
scale_colour_manual(values = colors, aesthetics = c("colour", "fill")); marg_pos_diff_pol


# Save Figures

eff_diff_pos_pol <- grid.arrange(marg_pos_pol, marg_pos_diff_pol, 
                                 ncol=2, nrow = 1)
eff_diff_pos_pol


# ------------------ Nonelective offices

### Calculate marginal effects

emm <- regrid(emmeans(m1p, ~ nonelec_d_eff | TAnonelec))
emm_data <- summary(regrid(emmeans(m1p, ~ nonelec_d_eff | TAnonelec)))
emm_pairs_data <- summary(pairs(emm, reverse = TRUE))
emm_pairspairs_data <- summary(pairs(pairs(emm, reverse = TRUE), by = NULL, reverse = TRUE))

# Save marginal effects for later

marg_p_diff_T_nonelec <- summary(pairs(pairs(emm), by = NULL))$estimate
marg_p_T0_nonelec <- emm_pairs_data[1, 3]
marg_p_T1_nonelec <- emm_pairs_data[2, 3]

#Figure marginal effects

colors = c("black", "grey50")
emm_pairs_data$col<- factor(emm_pairs_data$TAnonelec, 
                            levels = c("T1", "T0"), 
                            labels = c("On ballot", "Not on ballot"))
data <- emm_pairs_data
marg_pos_nonelec <- marg_plot(marg)
marg_pos_nonelec <- marg_pos_nonelec + guides(fill=FALSE) + theme(legend.position="none") +
theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank()) +
labs(colour = "Nonelective office", x="", y="Effect of nonelective office on positive preference votes", title="A") +
annotate("text", x=0.35, y=0.2, label = "Nonelective offices on ballot", vjust=1, hjust=1, size = 3.3, color="black") +
annotate("text", x=1.35, y=0.1, label = "Nonelective offices not on ballot", vjust=1, hjust=1, size = 3.3, color="grey50"); marg_pos_nonelec

# Figure difference marginal effects

data <- emm_pairspairs_data
marg_pos_diff_nonelec <- marg_diff_plot(marg)
marg_pos_diff_nonelec <- marg_pos_diff_nonelec +  labs(colour = "Nonelective office", x="", 
y="Difference of effects", 
title="B") +
scale_colour_manual(values = colors, aesthetics = c("colour", "fill")); marg_pos_diff_nonelec

# Save Figures

eff_diff_pos_nonelec <- grid.arrange(marg_pos_nonelec, marg_pos_diff_nonelec, 
                                 ncol=2, nrow = 1)
eff_diff_pos_nonelec

#--------------------------------------------------------------------------------------------#
#--------- PART 1c: Substantive effect size
#--------------------------------------------------------------------------------------------#

#---------------------------------------------------------------------- Change dependent variable in comparison to average

##### Negative preference votes (Share of average)

marg_T0_poloff/mean(d3_mn$n_pv)
marg_T1_poloff/mean(d3_mn$n_pv)
marg_diff_T_poloff/mean(d3_mn$n_pv) 

marg_T0_nonelec/mean(d3_mn$n_pv)
marg_T1_nonelec/mean(d3_mn$n_pv)
marg_diff_T_nonelec/mean(d3_mn$n_pv) 

##### Positive preference votes (Share of average)

marg_p_T0_poloff/mean(d3_mn$pos_rel)
marg_p_T1_poloff/mean(d3_mn$pos_rel)
marg_p_diff_T_poloff/mean(d3_mn$pos_rel)

marg_p_T0_nonelec/mean(d3_mn$pos_rel)
marg_p_T1_nonelec/mean(d3_mn$pos_rel)
marg_p_diff_T_nonelec/mean(d3_mn$pos_rel)

#---------------------------------------------------------------------- Predicted values

### Models

m1n <- glmmTMB(n_pv ~ nonswissname + relpos_c + precumulated + 
                 prof_c3 + sex_f + age_c3 + party_c4 + num_cand_c + 
                 TApoloff*poloff_d + TAnonelec*nonelec_d_eff + (1|list_id), 
               family=list(family="beta",link="logit"), data = d3_mn)
### Function

pred_val <- function(emm_data){
  emm_data <- summary(emm_data)
  emm_data <- emm_data[, c(1, 3, 4, 6, 7)]
  emm_data[,-1] <-round(emm_data[,-1], 3) 
  colnames(emm_data) <- coln
  emm_data[, 1] <- as.character(emm_data[, 1])
  emm_data <- rbind(emm_data, NotOnBallot)
  emm_data <- rbind(emm_data, OnBallot)
  emm_data <- emm_data[c(6, 1, 2, 5, 3, 4), ]
  return(emm_data)}

### Tables

# Negative preference votes, Political offices

emm_data <- regrid(emmeans(m1n, ~ poloff_d | TApoloff))
coln <- c("Political office", "Predicted values",  "SE", "Lower CI", "Upper CI")
NotOnBallot <- as.character(c("Political office not on ballot", "", "", "", ""))
OnBallot <- as.character(c("Political office on ballot", "", "", "", ""))
pred_neg_pol <- pred_val(emm_data)
print(xtable(pred_neg_pol), include.rownames=FALSE)

as.numeric(pred_neg_pol[3, 2])/as.numeric(pred_neg_pol[2, 2])
as.numeric(pred_neg_pol[6, 2])/as.numeric(pred_neg_pol[5, 2])


# Negative preference votes, nonelective offices

emm_data <- regrid(emmeans(m1n, ~ nonelec_d_eff | TAnonelec))
coln <- c("Nonelective office", "Predicted values",  "SE", "Lower CI", "Upper CI")
NotOnBallot <- as.character(c("Nonelective office not on ballot", "", "", "", ""))
OnBallot <- as.character(c("Nonelective office on ballot", "", "", "", ""))
pred_neg_nonelec <- pred_val(emm_data)
print(xtable(pred_neg_nonelec), include.rownames=FALSE)

as.numeric(pred_neg_nonelec[3, 2])/as.numeric(pred_neg_nonelec[2, 2])
as.numeric(pred_neg_nonelec[6, 2])/as.numeric(pred_neg_nonelec[5, 2])

# Positive preference votes, political offices

emm_data <- regrid(emmeans(m1p, ~ poloff_d | TApoloff))
coln <- c("Political office", "Predicted values",  "SE", "Lower CI", "Upper CI")
NotOnBallot <- as.character(c("Political office not on ballot", "", "", "", ""))
OnBallot <- as.character(c("Political office on ballot", "", "", "", ""))
pred_pos_pol <- pred_val(emm_data)
print(xtable(pred_pos_pol), include.rownames=FALSE)

as.numeric(pred_pos_pol[3, 2])/as.numeric(pred_pos_pol[2, 2])
as.numeric(pred_pos_pol[6, 2])/as.numeric(pred_pos_pol[5, 2])

# Positive preference votes, nonelective offices

emm_data <- regrid(emmeans(m1p, ~ nonelec_d_eff | TAnonelec))
coln <- c("Nonelective office", "Predicted values",  "SE", "Lower CI", "Upper CI")
NotOnBallot <- as.character(c("Nonelective office not on ballot", "", "", "", ""))
OnBallot <- as.character(c("Nonelective office on ballot", "", "", "", ""))
pred_pos_nonelec <- pred_val(emm_data)
print(xtable(pred_pos_nonelec), include.rownames=FALSE)


#--------------------------------------------------------------------------------------------#
#--- PART 2: Impact information about competence on effect of candidate name
#--------------------------------------------------------------------------------------------#

#---------------------------------------------------------------------- Model

m2n <- glmmadmb(n_pv ~ relpos_c + precumulated + 
                 poloff_d + nonelec_d_eff + 
                 party_c4 + num_cand_c +
                 nonswissname*TApolinv + factor(prof_c3)*TApolinv + sex_f*TApolinv + age_c3*TApolinv +
                 (1 | list_id), 
family="beta", data = d3_mn)
summary(m2n)

m2p <- glmer(pos_rel ~  relpos_c + precumulated + 
              poloff_d + nonelec_d_eff + 
              party_c4 + num_cand_c +
              nonswissname*TApolinv + factor(prof_c3)*TApolinv + sex_f*TApolinv + age_c3*TApolinv +
              (1 | list_id), nAGQ=0, family=inverse.gaussian(link="log"), data=d3_mp)
summary(m2p)

hist(d3$tot_rel)

#---------------------------------------------------------------------- Table

custom.coef.1 <- list("(Intercept)" = "Intercept", 
                   "nonswissname" = "Non-Swiss name", 
                   "TApolinv" = "Political experience on ballot",
                   "factor(prof_c3)2" = "Profession = medium-skilled", 
                   "factor(prof_c3)3" = "Profession = low-skilled", 
                   "sex_f" = "Female", 
                   "age_c31" = "Age: 31-50 years ", 
                   "age_c32" = "Age: 50+ years", 
                   "nonswissname:TApolinv" = "   x Non-Swiss name", 
                   "TApolinv:factor(prof_c3)2" = "   x Profession (medium-skilled)", 
                   "TApolinv:factor(prof_c3)3" = "   x Profession (low-skilled)", 
                   "TApolinv:sex_f" = "   x Female", 
                   "TApolinv:age_c31" = "   x Age (31-50)", 
                   "TApolinv:age_c32" = "   x Age (50+)")

texreg(list(m2n, m2p), 
custom.model.names = c("DV: negative preference votes", "DV: positive preference votes"),
omit.coef = c(2, 3, 4, 5, 6, 7, 8, 9),
custom.coef.map = custom.coef.1,
reorder.coef = c(2, 4, 5, 6, 7, 8, 3, 9, 10, 11, 12, 13, 14, 1),
caption="Effect of political experience on the ballot and interaction with various candidate characteristics on preference votes (negative and positive)",
caption.above = TRUE, stars = c(0.01, 0.05, 0.1))

#---------------------------------------------------------------------- Marginal effects negative preference votes with uncertainty: table and figure

### Model

m2n <- glmmTMB(n_pv ~ relpos_c + precumulated + 
                 poloff_d + nonelec_d_eff + 
                 party_c4 + num_cand_c +
                 nonswissname*TApolinv + prof_c3*TApolinv + 
                 sex_f*TApolinv + age_c3*TApolinv + (1|list_id), 
               family=list(family="beta",link="logit"), data = d3_mn)

### Calculate marginal effects

emm <- regrid(emmeans(m2n, ~ nonswissname | TApolinv))
emm_data <- summary(regrid(emmeans(m2n, ~ nonswissname | TApolinv)))
emm_pairs_data <- summary(pairs(emm, reverse = TRUE))
emm_pairspairs_data <- summary(pairs(pairs(emm, reverse = TRUE), by = NULL, reverse = TRUE))

#Figure marginal effects

colors = c("black", "grey50")
emm_pairs_data$col <- factor(emm_pairs_data$TApolinv, 
                               levels = c(1, 0), 
                               labels = c("On ballot", "Not on ballot"))
data <- emm_pairs_data
marg_neg_nonswiss <- marg_plot(marg)
marg_neg_nonswiss <- marg_neg_nonswiss + guides(fill=FALSE) + theme(legend.position="none") +
theme(axis.text.y=element_blank(), axis.ticks.y=element_blank()) +
labs(x="", y="Effect of non-Swiss name on negative preference votes", title="A") +
annotate("text", x=0.35, y=0.025, label = "Political experience on ballot", vjust=1, hjust=1, size = 3.3, color="black") +
annotate("text", x=1.35, y=0.04, label = "Political experience not on ballot", vjust=1, hjust=1, size = 3.3, color="grey50"); marg_neg_nonswiss 

# Figure difference marginal effects

data <- emm_pairspairs_data
marg_neg_diff_pol <- marg_diff_plot(marg)
marg_neg_diff_pol <- marg_neg_diff_pol +  labs(colour = "Candidate name", x="", 
y="Difference of effects", 
title="B"); marg_neg_diff_pol

# Save Figures
 
eff_diff_name <- grid.arrange(marg_neg_nonswiss, marg_neg_diff_pol, 
                            ncol=2, nrow = 1)
eff_diff_name

#---------------------------------------------------------------------- Positive preference votes

d3_mp$TApolinv <- factor(d3_mp$TApolinv)
d3_mp$prof_c3 <- factor(d3_mp$prof_c3)

m2p <- glmer(pos_rel ~ relpos_c + precumulated + 
               poloff_d + nonelec_d_eff + 
               party_c4 + num_cand_c +
               nonswissname*TApolinv + prof_c3*TApolinv + sex_f*TApolinv + age_c3*TApolinv + (1| list_id), 
             family= inverse.gaussian(link="log"), nAGQ=0, data=d3_mp)


### Calculate marginal effects

emm <- regrid(emmeans(m2p, ~ nonswissname | TApolinv))
emm_data <- summary(regrid(emmeans(m2p, ~ nonswissname | TApolinv)))
emm_pairs_data <- summary(pairs(emm, reverse = TRUE))
emm_pairspairs_data <- summary(pairs(pairs(emm, reverse = TRUE), by = NULL, reverse = TRUE))

#Figure marginal effects

colors = c("black", "grey50")
emm_pairs_data$col <- factor(emm_pairs_data$TApolinv, 
                             levels = c(1, 0), 
                             labels = c("On ballot", "Not on ballot"))
data <- emm_pairs_data
marg_pos_nonswiss <- marg_plot(marg)
marg_pos_nonswiss <- marg_pos_nonswiss + guides(fill=FALSE) + theme(legend.position="none") +
theme(axis.text.y=element_blank(), axis.ticks.y=element_blank()) +
labs(x="", y="Effect of non-Swiss name on positive preference votes", title="A") +
annotate("text", x=0.35, y=-0.1, label = "Political experience on ballot", vjust=1, hjust=1, size = 3.3, color="black") +
annotate("text", x=1.35, y=-0.12, label = "Political experience not on ballot", vjust=1, hjust=1, size = 3.3, color="grey50"); marg_pos_nonswiss

# Figure difference marginal effects

data <- emm_pairspairs_data
marg_pos_diff_pol <- marg_diff_plot(marg)
marg_pos_diff_pol <- marg_pos_diff_pol +  labs(colour = "Candidate name", x="", 
y="Difference of effects", 
title="B"); marg_pos_diff_pol

eff_diff_name_pos <- grid.arrange(marg_pos_nonswiss, marg_pos_diff_pol, 
                              ncol=2, nrow = 1)
eff_diff_name_pos 

#---------------------------------------------------------------------- Substantive effect size

### Negative preference votes

pred_neg_nonswiss <- regrid(emmeans(m1n, ~ nonswissname))
pred_neg_nonswiss <- summary(pred_neg_nonswiss)
pred_neg_nonswiss <- pred_neg_nonswiss[, c(1, 2, 3, 5, 6)]
pred_neg_nonswiss$nonswissname <- factor(pred_neg_nonswiss$nonswissname, levels = c(0, 1), labels = c("Swiss-name", "Non-Swiss name"))
colnames(pred_neg_nonswiss) <- c("Name", "Predicted values",  "SE", "Lower CI", "Upper CI")
print(xtable(pred_neg_nonswiss, digits=c(0, 0, 3, 3, 3, 3), caption = "Predicted negative preference votes for candidate name (Swiss, non-Swiss)"), include.rownames=FALSE)

as.numeric(pred_neg_nonswiss[2, 2])/as.numeric(pred_neg_nonswiss[1, 2])

### Positive preference votes

pred_pos_nonswiss <- regrid(emmeans(m1p, ~ nonswissname))
pred_pos_nonswiss <- summary(pred_pos_nonswiss)
pred_pos_nonswiss <- pred_pos_nonswiss[, c(1, 2, 3, 5, 6)]
pred_pos_nonswiss$nonswissname <- factor(pred_pos_nonswiss$nonswissname, levels = c(0, 1), labels = c("Swiss-name", "Non-Swiss name"))
colnames(pred_pos_nonswiss) <- c("Non-Swiss name", "Predicted values",  "SE", "Lower CI", "Upper CI")
print(xtable(pred_pos_nonswiss, digits=c(0, 0, 3, 3, 3, 3), caption = "Predicted positive preference votes for candidate name (Swiss, non-Swiss)"), include.rownames=FALSE)

as.numeric(pred_pos_nonswiss[2, 2])/as.numeric(pred_pos_nonswiss[1, 2])

